/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package DAO;

import DTO.News.New;
import DTO.News.NewDetail;
import DTO.News.News;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import util.DBUtil;

/**
 *
 * @author ThanhTai
 */
public class NewDAO {

    public News getAllNews(String condition) throws SQLException, Exception {

        DBUtil util = new DBUtil();
        Connection conn = null;
        Statement stm = null;
        StringBuilder strBuilder = new StringBuilder();
        News news = new News();
        ResultSet rs = null;

        try {
            Class.forName(util.getDriverName());
            DriverManager.registerDriver(new com.microsoft.sqlserver.jdbc.SQLServerDriver());
            conn = DriverManager.getConnection(util.getURL(), util.getUsername(), util.getPassword());
            strBuilder.append("SELECT * FROM New ");
            if (condition != null && !condition.equals("")) {
                strBuilder.append(condition);
            }
            stm = conn.createStatement();
            rs = stm.executeQuery(strBuilder.toString());
            while (rs.next()) {
                New ne = new New(rs.getInt("ID"), rs.getString("title"), rs.getString("image"), rs.getString("header"), rs.getString("closing"), rs.getLong("date"), rs.getString("status"));
                String sql = "SELECT * FROM NewDetail WHERE NewID = " + ne.getID();
                stm = conn.createStatement();
                ResultSet rsDetail = stm.executeQuery(sql);
                while (rsDetail.next()) {
                    NewDetail newDetail = new NewDetail(rsDetail.getInt("newDetailID"),rsDetail.getInt("newID"),rsDetail.getString("paragrap"));
                    ne.addNewDetail(newDetail);
                }
                news.addNew(ne);
            }
            return news;
        } catch (SQLException e) {
            throw (e);
        } catch (Exception e) {
            throw (e);
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
                return null;
            }
            try {
                if (stm != null) {
                    stm.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
                return null;
            }
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
                return null;
            }
        }
    }
}
